package cc.fine.svc.main.controller.tbl;


import cc.fine.svc.common.utils.R;
import cc.fine.svc.main.bean.dto.UserInfoDto;
import cc.fine.svc.main.bean.es.UserUpdateEsEntity;
import cc.fine.svc.main.bean.po.TblUser;
import cc.fine.svc.main.bean.vo.UserVo;
import cc.fine.svc.main.service.tbl.TblUserService;
import cc.fine.svc.security.utils.IPUtils;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wyihe
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/user")
@Api(description = "用户相关接口")
public class TblUserController {

    @Autowired
    private TblUserService userService;

    @ApiOperation("获取用户相关信息，包含关注数粉丝数等等信息")
    @GetMapping("/{userId}")
    public R get(@PathVariable String userId) {
        UserInfoDto dto = userService.getInfo(userId);

        return R.ok().data("data", dto);
    }

    @ApiOperation("关键字查找用户,可以是fineId、用户名")
    @GetMapping("/search/{page}/{limit}")
    public R search(
            @PathVariable Integer page,
            @PathVariable Integer limit,
            String keyword) {
        List<Map<String, Object>> res = userService.search(keyword, page, limit);
        return R.ok().data("data", res);
    }

    @ApiOperation("用户编辑信息")
    @PutMapping("/{userId}")
    public R edit(@PathVariable String userId,
                  @RequestBody(required = false) UserUpdateEsEntity entity) {

        userService.updateInfo(userId, entity);

        return R.ok();
    }

    @ApiOperation("获ip信息")
    @GetMapping("/ip")
    public R ip(HttpServletRequest request) throws Exception{

        String ip = IPUtils.getIp(request);

        OkHttpClient client = new OkHttpClient();
        Request build = new Request
                .Builder()
                .url("https://toolwa.com/api/v1?action=ip&ip=" + ip)
                .build();

        Response response = client.newCall(build).execute();
        String res = response.body().string();

        return R.ok().data("data", JSON.parse(res));
    }

}

